"""
# coding     : utf-8 
# Time       : 2025/6/9 11:33
# Author     : chenxianb
# version    : python 3.8.2
# Description: 获取中国大学排名第一页的学校
"""
import os.path
import time

import bs4
import openpyxl
import requests
from bs4 import BeautifulSoup


def getHTMLText(url):
    header = {"User-Agent": "Mozilla/5.0"}
    try:
        r = requests.get(url, timeout=30, headers=header)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return ""


def getData(html):
    lst = []
    soup = BeautifulSoup(html, "html.parser")
    # 每个大学都是一个tr标签，且这些tr都是tbody的子节点
    # 遍历tr标签，遍历一次就获取一个学校的信息
    for tr in soup.find('tbody').children:
        # 判断tr是不是标签类型,
        if isinstance(tr, bs4.element.Tag):
            # 获取每个学校tr标签中的子节点td
            tds = tr.contents
            # 排名
            index = tds[0].text.strip()
            # 名字
            university = tds[1].text.strip()
            name = university.split(" ")[0].strip()
            level = university.split(" ")[-1].strip()
            # 城市
            city = tds[2].text.strip()
            # 类型
            universityType = tds[3].text.strip()
            # 总分
            score = tds[4].text.strip()

            lst.append([index, name, city, universityType, level, score])

    return lst


def writeToExcel(lst):
    timestamp = int(time.time())
    file = f"./排名{timestamp}.xlsx"
    if os.path.exists(file):
        print("文件已存在")
    wb = openpyxl.Workbook(file)
    table = wb.create_sheet("大学排名", 0)
    title = ["排名", "学校", "城市", "学校类型", "级别", "总分"]
    table.append(title)
    for item in lst:
        table.append(item)

    wb.save(file)
    print("文件已保存")


if __name__ == '__main__':
    url = "https://www.shanghairanking.cn/rankings/bcur/202511"

    html = getHTMLText(url)
    lst = getData(html)
    writeToExcel(lst)
